# coding=utf-8
import json

import requests
from lxml import etree


class QiuBai(object):
    def __init__(self):
        self.temp_url = "https://www.qiushibaike.com/hot/page/{}"
        self.headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36"}

    def get_url_list(self):
        return [self.temp_url.format(i) for i in range(1, 14)]

    def parse_url(self, url):
        response = requests.get(url, headers=self.headers)
        return response.content.decode()

    def get_content_list(self, html_str):
        html = etree.HTML(html_str)
        div_list = html.xpath("//div[@id='content-left']/div")
        content_list = []
        for div in div_list:
            item = {}
            item["user_name"] = div.xpath(".//h2/text()")[0].strip()
            item["content"] = [i.strip() for i in div.xpath(".//div[@class='content']/span/text()")]
            content_list.append(item)
        return content_list

    def save_content_list(self, content_list):
        for content in content_list:
            print(content)
        pass

    def run(self):
        # 准备url
        url_list = self.get_url_list()

        # 遍历发送请求，获取响应
        for url in url_list:
            html_str = self.parse_url(url)

            # 提取数据
            content_list = self.get_content_list(html_str)

            # 保存
            self.save_content_list(content_list)


if __name__ == '__main__':
    qiubai = QiuBai()
    qiubai.run()

